<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
</body>
<script>
    // 1. 测试js的getter/setter 
    // 使用点号获取对象的属性，底层会调用对象的get方法，同样，赋值会调用set方法
    let man = {
        name: 'Bob',
        _age_: 1,
        get age() {
            console.log('get age:', this._age_)
            return this._age_
        },
        set age(val) {
            console.log('set age:', val)
            this._age_ = val
        }
    } 
    man.age = 18 
    console.log('man.age:', man.age)


    // 2. 测试Proxy
    let target = {
        name: '小明',
        age: 15
    }

    let handler = {
        get(target, propKey, receive) {
            if(propKey in target) {
                console.log('get success')
            } else {
                console.log('get error')
            }
            return Reflect.get(target, propKey, receive)
        },
        set(target, propKey, value, receiver) {
            if(propKey === 'age') {
                if(!Number.isInteger(value)) {
                    throw new TypeError('The age is not an integer')
                } else {
                    console.log('set success')
                }
            } else {
                console.log('set success')
            }
            return Reflect.set(target, propKey, value, receiver)
        },
        has(target, propKey) {
            console.log('handle has')
            return propKey in target 
        }
    }

    let pro = new Proxy(target, handler)

    // 操作代理对象，从而间接操作目标对象，在操作过程中可以加入一些处理逻辑 
    console.log(pro.name) // 通过代理获取属性时，会调用get方法 
    console.log(pro.gender) 
    pro.name = 'Jack'
    // pro.age = '12' // 抛出异常，往下不再执行 
    pro.age = 12
    pro.gender = 'male'
    console.log('target:', target) // {name: 'Jack', age: 12, gender: 'male'} 
    console.log('gender' in pro) // true 
</script>
</html>